package com.rfid.acs;

import android.util.Log;

import com.rfid.acs.bean.BookBean;
import com.rfid.acs.net.IBookNet;
import com.rfid.acs.net.ResponseWrapper;
import com.rfid.acs.net.bean.ReaderInfoBean;
import com.rfid.acs.net.bean.RestoreBookBean;
import com.rfid.acs.net.exception.NoRecordException;
import com.rfid.acs.net.tcp.IRequest;
import com.rfid.acs.net.tcp.TcpClient;
import com.rfid.common.log.LogUtils;
import com.rfid.manager.BookManager;
import com.rfid.manager.ConfigManager;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


public class AcsBookNet implements IBookNet {

    @Override
    public Observable<BookBean> searchBookWithBarcode(String barcode) {
        SearchBookRequestBean requestBean = new SearchBookRequestBean();
        requestBean.setBookNo(barcode);
        requestBean.setMacAddress(ConfigManager.INSTANCE.getDeviceNo());
        requestBean.setDevicesNo(ConfigManager.INSTANCE.getDeviceNo());

        TcpClient tcpClient = ConfigManager.INSTANCE.getTcpClient();
        return tcpClient.request(requestBean)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Function<String, BookBean>() {
                    @Override
                    public BookBean apply(String response) throws Exception {
                        SearchBookResponseBean bean = new SearchBookResponseBean(response);
                        if (!bean.isSuccess()) {
//                            if (bean.getHintMessage() != null && bean.getHintMessage().contains("馆藏记录")) {
//                                throw new NoRecordException(bean.getHintMessage());
//                            } else {
//                                throw new RuntimeException(bean.getHintMessage());
//                            }
                        }
                        return bean.convertToBookBean();
                    }
                });
    }

    @Override
    public Observable<BookBean> borrowBook(String barcode, String readerNo, String password) {
        BorrowBookRequestBean requestBean = new BorrowBookRequestBean();
        requestBean.setMacAddress(ConfigManager.INSTANCE.getDeviceNo());
        requestBean.setDevicesNo(ConfigManager.INSTANCE.getDeviceNo());
        requestBean.setBookNo(barcode);
        requestBean.setReaderNo(readerNo);
        requestBean.setPassword(password);

        TcpClient tcpClient = ConfigManager.INSTANCE.getTcpClient();

        return tcpClient.request(requestBean)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Function<String, BookBean>() {
                    @Override
                    public BookBean apply(String response) throws Exception {

                        BorrowBookResponseBean responseBean = new BorrowBookResponseBean(response);

//                        if (!responseBean.isSuccess()) {
//                            if (responseBean.getHintMessage() != null && responseBean.getHintMessage().contains("馆藏记录")) {
//                                throw new NoRecordException(responseBean.getHintMessage());
//                            } else {
//                                throw new RuntimeException(responseBean.getHintMessage());
//                            }
//                        }
                        BookBean bookBean = new BookBean();
                        bookBean.setBookName(responseBean.getBookTitle());
                        bookBean.setBookId(responseBean.getBookNo());
                        bookBean.setLimitDate(responseBean.getReturnTime());
                        bookBean.setHintMessage(responseBean.getHintMessage());
                        bookBean.setSuccess(responseBean.isSuccess());
                        return bookBean;
                    }
                });
    }

    @Override
    public Observable<BookBean> renewalBook(String barcode, String readerNo, String password) {
        BorrowBookRequestBean requestBean = new BorrowBookRequestBean();
        requestBean.setMacAddress(ConfigManager.INSTANCE.getDeviceNo());
        requestBean.setDevicesNo(ConfigManager.INSTANCE.getDeviceNo());
        requestBean.setBookNo(barcode);
        requestBean.setReaderNo(readerNo);
        requestBean.setPassword(password);
        requestBean.setRenewal(true);//这里设置是续借,其他逻辑和借书一样

        TcpClient tcpClient = ConfigManager.INSTANCE.getTcpClient();

        return tcpClient.request(requestBean)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Function<String, BookBean>() {
                    @Override
                    public BookBean apply(String response) throws Exception {

                        BorrowBookResponseBean responseBean = new BorrowBookResponseBean(response);

                        if (!responseBean.isSuccess()) {
//                            if (responseBean.getHintMessage() != null && responseBean.getHintMessage().contains("馆藏记录")) {
//                                throw new NoRecordException(responseBean.getHintMessage());
//                            } else {
//                                throw new RuntimeException(responseBean.getHintMessage());
//                            }
                        }

                        BookBean bookBean = new BookBean();
                        bookBean.setBookName(responseBean.getBookTitle());
                        bookBean.setBookId(responseBean.getBookNo());
                        bookBean.setLimitDate(responseBean.getReturnTime());
                        bookBean.setHintMessage(responseBean.getHintMessage());
                        bookBean.setSuccess(responseBean.isSuccess());
                        return bookBean;
                    }
                });
    }

    @Override
    public Observable<RestoreBookBean> restoreBook(String barcode) {
        RestoreBookRequestBean requestBean = new RestoreBookRequestBean();

        requestBean.setMacAddress(ConfigManager.INSTANCE.getDeviceNo());
        requestBean.setDevicesNo(ConfigManager.INSTANCE.getDeviceNo());
        requestBean.setBookNo(barcode);

        TcpClient tcpClient = ConfigManager.INSTANCE.getTcpClient();
        return tcpClient.request(requestBean)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Function<String, RestoreBookBean>() {
                    @Override
                    public RestoreBookBean apply(String response) throws Exception {

                        RestoreBookResponseBean responseBean = new RestoreBookResponseBean(response);

//                        if (!responseBean.isSuccess()) {
//                            if (responseBean.getHintMessage() != null && responseBean.getHintMessage().contains("馆藏记录")) {
//                                throw new NoRecordException(responseBean.getHintMessage());
//                            } else {
//                                throw new RuntimeException(responseBean.getHintMessage());
//                            }
//                        }

                        RestoreBookBean restoreBookBean = new RestoreBookBean();
                        restoreBookBean.setBookName(responseBean.getBookName());
                        restoreBookBean.setBookNo(responseBean.getBookNo());
                        restoreBookBean.setSuccess(responseBean.isSuccess());
                        restoreBookBean.setHintMessage(responseBean.getHintMessage());

                        return restoreBookBean;
                    }
                });
    }

    @Override
    public Observable<ReaderInfoBean> searchReaderInfo(String readerNo, String password) {
        SearchReaderRequestBean requestBean = new SearchReaderRequestBean();
        requestBean.setMacAddress(ConfigManager.INSTANCE.getDeviceNo());
        requestBean.setDevicesNo(ConfigManager.INSTANCE.getDeviceNo());
        requestBean.setReaderNo(readerNo);
        requestBean.setPassword(password);

        TcpClient tcpClient = ConfigManager.INSTANCE.getTcpClient();
        return tcpClient.request(requestBean)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Function<String, ReaderInfoBean>() {
                    @Override
                    public ReaderInfoBean apply(String response) throws Exception {
                        SearchReaderResponseBean bean = new SearchReaderResponseBean(response);
//                        if (!bean.isSuccess()) {
//                            throw new RuntimeException(bean.getHintMessage());
//                        }
                        return bean.convertToReaderBean();
                    }
                }).flatMap(new Function<ReaderInfoBean, Observable<ReaderInfoBean>>() {
                    @Override
                    public Observable<ReaderInfoBean> apply(final ReaderInfoBean readerBean) throws Exception {
                        LogUtils.v(readerBean);
                        return BookManager.INSTANCE.searchBooksWithBarcode(readerBean.getAllBookNos())
                                .map(new Function<List<BookBean>, ReaderInfoBean>() {
                                    @Override
                                    public ReaderInfoBean apply(List<BookBean> bookBeans) throws Exception {
                                        readerBean.setAllBooks(bookBeans);
                                        return readerBean;
                                    }
                                });
                    }
                });
    }

    @Override
    public Observable<List<BookBean>> searchBooksWithBarcode(List<String> strings) {
        final TcpClient client = ConfigManager.INSTANCE.getTcpClient();

        //请求数据封装
        final List<IRequest> beans = new ArrayList<IRequest>();
        for (String str : strings) {
            SearchBookRequestBean bean = new SearchBookRequestBean();
            bean.setDevicesNo(ConfigManager.INSTANCE.getDeviceNo());
            bean.setMacAddress(ConfigManager.INSTANCE.getDeviceNo());
            bean.setBookNo(str);
            Log.d("NETLOG", "查询" + str);
            beans.add(bean);
        }

        return client.requestWrapperSysc(beans)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Function<List<ResponseWrapper>, List<BookBean>>() {
                    @Override
                    public List<BookBean> apply(List<ResponseWrapper> wrappers) throws Exception {
                        List<BookBean> result = new ArrayList<BookBean>();
                        for (ResponseWrapper wrapper : wrappers) {
                            if (wrapper != null) {
                                SearchBookResponseBean responseBean = new SearchBookResponseBean(wrapper.getResponseStr());

                                if (!responseBean.isSuccess()) {
//                                    if (responseBean.getHintMessage() != null && responseBean.getHintMessage().contains("馆藏记录")) {
//                                        throw new NoRecordException(responseBean.getHintMessage());
//                                    } else {
//                                        throw new RuntimeException(responseBean.getHintMessage());
//                                    }
                                    continue;
                                }

                                BookBean bookBean = responseBean.convertToBookBean();

                                //从请求数据中找到对应tagid
                                SearchBookRequestBean requestBean = (SearchBookRequestBean) wrapper.getRequestBean();
                                bookBean.setTagId(requestBean.getTagId());
                                result.add(bookBean);
                            }
                        }
                        return result;
                    }
                });
    }

}
